package controllers.payapi;

/**
 * Created by buhaoba on 15/12/22.
 */

import com.pingplusplus.model.Charge;
import enums.GoodsType;
import enums.OrderStatus;
import enums.PaymentType;
import goods.Goods;
import helper.PingppHelper;
import jodd.util.StringUtil;
import models.constants.DeletedStatus;
import models.venue.curriculum.Curriculum;
import models.venue.curriculum.WebUserCurriculum;
import models.weixin.WebUser;
import models.weixin.amount.RechargeCombo;
import models.weixin.amount.WebUserAccount;
import models.weixin.amount.WebUserAccountHistory;
import notice.OrderNotice;
import order.Order;
import order.OrderItem;
import play.Logger;
import play.mvc.Controller;
import util.common.DateUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付处理.
 */
public class PaymentFlows extends Controller {

    /**
     * 得到支付charge.
     * 微信
     */
    public static void qrChargeJson(String orderNumber , String payType) {
        Logger.info("LOG01811: chargeJson for OrderNumber:" + orderNumber);
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findByOrderNumber(orderNumber);
        Logger.info("Order : %s" , order);
        if (order == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单不存在或已删除");
            renderJSON(resultMap);
        }
        if (order.status != OrderStatus.UNPAID) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单状态不是未付款状态，不能支付");
            renderJSON(resultMap);
        }
        Charge charge = PingppHelper.createScanCodePay(order , payType);
        if (charge != null) {
            Logger.info("来自" +order.merchant.name + "订单号:" + orderNumber +"地址:"+order.address);
            Map<String, Object> credentialMap = charge.getCredential();
            Logger.info("credentialMap : %s " , credentialMap);
            if (credentialMap == null) {
                resultMap.put("success" , false);
                resultMap.put("msg" , "订单生成支付凭证失败，请刷新重试");
                renderJSON(resultMap);
            }
            Logger.info("qrcode : %s " , credentialMap.get(payType));
            resultMap.put("success" , true);
            resultMap.put("qrcode" , credentialMap.get(payType));
            renderJSON(resultMap);
        }
    }


    /**
     * 现金付款
     * @param orderNumber
     * @param phone
     */
    public static void cash(String orderNumber , String phone) {
        phone = StringUtil.isBlank(phone) ? "18602190971" : phone;
        Logger.info("LOG01811: chargeJson for OrderNumber:" + orderNumber  + " | Phone : " + phone);
        Map<String , Object> resultMap = new HashMap<>();
        Order order = Order.findByOrderNumber(orderNumber);
        Logger.info("Order : %s" , order);

        WebUser webUser = WebUser.findByPhone(phone);
        if(webUser == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "会员卡用户不存在");
            renderJSON(resultMap);
        }


        if (order == null) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单不存在或已删除");
            renderJSON(resultMap);
        }
        if (order.status != OrderStatus.UNPAID) {
            resultMap.put("success" , false);
            resultMap.put("msg" , "订单状态不是未付款状态，不能支付");
            renderJSON(resultMap);
        }

        order.paymentType = PaymentType.CASH;
        order.status = OrderStatus.PAID;
        order.webUser = webUser;
        order.save();

        if(order.goodsType == GoodsType.RECHARGE) {
            OrderItem orderItem = OrderItem.getByOrder(order);
            RechargeCombo rechargeCombo = RechargeCombo.findById(orderItem.goods.serialId);
            WebUserAccount webUserAccount = WebUserAccount.findByWebUserAndGoodsType(webUser , rechargeCombo.goodsType);
            Double giveMoney = rechargeCombo == null ? 0d : rechargeCombo.giveAmount;
            if(webUserAccount == null) {
                webUserAccount =  new WebUserAccount(webUser , order.amount + giveMoney , rechargeCombo.goodsType).save();
            } else {
                webUserAccount.amount += order.amount + giveMoney;
                webUserAccount.save();
            }
            new WebUserAccountHistory(webUserAccount , order.amount , giveMoney , "会员卡充值").save();
        }

        if(order.goodsType == GoodsType.CURRICULUM) {
//            Logger.info("----------------------------新建用户课程记录表 paymentFlows----------------------------");

            OrderItem orderItem = OrderItem.getByOrder(order);
            Curriculum curriculum = Curriculum.findById(orderItem.goods.serialId);
            Date beginAt = new Date();
            int days = 0;
            try {
             days = DateUtil.getDaysBetween(curriculum.startTime , curriculum.endTime);
            }catch (Exception e){
                e.printStackTrace();
            }
            Date endAt = DateUtil.getAfterDate(beginAt , days);
            //TODO
            WebUserCurriculum webUserCurriculum = new WebUserCurriculum();
            webUserCurriculum.webUser = webUser;
            webUserCurriculum.createAt = new Date();
            webUserCurriculum.curriculum = curriculum;
            webUserCurriculum.order = order ;
            webUserCurriculum.quantity = curriculum.quantity;
            webUserCurriculum.beUsedNum = 0 ;
            webUserCurriculum.residueNum = curriculum.quantity;
            webUserCurriculum.startTime = beginAt;
            webUserCurriculum.endTime = endAt;
            webUserCurriculum.deleted= DeletedStatus.UN_DELETED;
            webUserCurriculum.save();


        }



        resultMap.put("success" , true);
        renderJSON(resultMap);
    }


}
